/* eslint-disable no-case-declarations */
import React, { Component } from 'react'
import { Picker } from '@tarojs/components'
import region from './data'

export default class RegionPicker extends Component {
  state = {
    range: [],
    value: [0, 0, 0]
  }

  componentDidMount() {
    const temp = [];
    temp.push(region);
    temp.push(region[0].children);
    temp.push(region[0].children[0].children);
    this.setState({
      range: temp
    })
  }

  onChange = e => {
    const { onChange } = this.props
    const detail = { code: [], value: [] }
    const valueTemp = e.detail.value;
    const province = region[valueTemp[0]]
    if (!province) return
    detail.code.push(province.code)
    detail.value.push(province.name)
    const city = province.children?.[valueTemp[1]]
    if (city) {
      detail.code.push(city.code)
      detail.value.push(city.name)
    }
    const district = city.children?.[valueTemp[2]];

    if (district) {
      detail.code.push(district.code)
      detail.value.push(district.name)
    }
    this.setState({
      value: valueTemp
    }, () => {
      onChange?.({ detail })
    })
  }

  onColumnChange = e => {
    const { range: rangeTemp, value: valueTemp } = this.state
    const { column } = e.detail;
    const row = e.detail.value;
    valueTemp[column] = row;
    switch (column) {
      case 0:
        let cityTemp = [];
        let districtTemp = [];
        if (region[row].children.length) {
          cityTemp = region[row].children;
        }
        if (region[row].children[0].children.length) {
          districtTemp = region[row].children[0].children;
        }
        valueTemp[1] = 0;
        valueTemp[2] = 0;
        rangeTemp[1] = cityTemp;
        rangeTemp[2] = districtTemp;
        break;
      case 1:
        let districtTemp2 = [];
        if (region[valueTemp[0]].children[row].children.length) {
          districtTemp2 = region[valueTemp[0]].children[row].children;
        }
        valueTemp[2] = 0;
        rangeTemp[2] = districtTemp2;
        break;
      case 2:
        break;
      default:
        break;
    }
    this.setState({
      range: [...rangeTemp],
      value: valueTemp
    })
  }

  render() {
    const { range, value } = this.state
    const { children } = this.props
    return (
      <Picker
        mode="multiSelector"
        onChange={this.onChange}
        onColumnChange={this.onColumnChange}
        range={range}
        rangeKey="name"
        value={value}
      >
        {children}
      </Picker>
    )
  }
}
